import cv2
import numpy as np
import urllib.request


class Track(object):
    def __init__(self, proxy_username=None, proxy_password=None):
        self.request = urllib.request
        if(proxy_username is not None):
            proxies = {'http': 'http://{}:{}@proxy.huawei.com:8080/'.format(proxy_username, proxy_password), 'https': 'http://{}:{}@proxy.huawei.com:8080/'.format(proxy_username, proxy_password)}
            self.proxy_handler = self.request.ProxyHandler(proxies)
            self.auth = self.request.HTTPBasicAuthHandler()
            self.opener = self.request.build_opener(self.proxy_handler, self.auth, self.request.HTTPHandler)
            self.request.install_opener(self.opener)

    def getTrack(self, slider_url, background_url) -> list:
        distance = self.get_slide_distance(slider_url, background_url)
        result = self.gen_normal_track(distance)
        return result

    @staticmethod
    def gen_normal_track(distance):
        def norm_fun(x, mu, sigma):
            pdf = np.exp(-((x - mu) ** 2) / (2 * sigma ** 2)) / (sigma * np.sqrt(2 * np.pi))
            return pdf

        result = []
        for i in range(-10, 10, 1):
            result.append(norm_fun(i, 0, 1) * distance)
        result.append(sum(result) - distance)
        return result

    @staticmethod
    def gen_track(distance):  # distance为传入的总距离
        # 移动轨迹
        result = []
        # 当前位移
        current = 0
        # 减速阈值
        mid = distance * 4 / 5
        # 计算间隔
        t = 0.2
        # 初速度
        v = 1

        while current < distance:
            if current < mid:
                # 加速度为2
                a = 4
            else:
                # 加速度为-2
                a = -3
            v0 = v
            # 当前速度
            v = v0 + a * t
            # 移动距离
            move = v0 * t + 1 / 2 * a * t * t
            # 当前位移
            current += move
            # 加入轨迹
            result.append(round(move))
        return result

    def __loadImageFromNet(self, url):
        resp = self.request.urlopen(url)
        image = np.asarray(bytearray(resp.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        return image

    def __debugImage(self, title, img):
        cv2.imshow(title, img)
        cv2.waitKey(0)
        
    def get_slide_distance(self, slider_url, background_url):
        slider_pic = self.__loadImageFromNet(slider_url)
        background_pic = cv2.cvtColor(self.__loadImageFromNet(background_url),cv2.COLOR_RGBA2RGB)
        slider_pic_gray = cv2.cvtColor(slider_pic, cv2.COLOR_BGR2GRAY)
        slider_pic_gray = cv2.cvtColor(abs(255 - slider_pic_gray),cv2.COLOR_RGBA2RGB)
        result = cv2.matchTemplate(slider_pic_gray, background_pic, cv2.TM_CCOEFF_NORMED)
        top, left = np.unravel_index(result.argmax(), result.shape)
        return left * 340 / 552

